package main

import (
	"context"
	"fmt"
	"go_knowledge/rpc/grpc/proto"
	"google.golang.org/grpc"
	"io"
	"log"
	"net"
)

type HelloServiceImpl struct{}

func (p *HelloServiceImpl) Hello(ctx context.Context, args *proto.String) (*proto.String, error) {
	reply := &proto.String{Value: "hello:" + args.GetValue()}
	return reply, nil
}

func (p *HelloServiceImpl) Channel(stream proto.HelloService_ChannelServer) error {
	for {
		args, err := stream.Recv()
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}

		reply := &proto.String{Value: "hello:" + args.GetValue()}
		fmt.Println(reply)
		err = stream.Send(reply)
		if err != nil {
			return err
		}
	}
}

type LoginServerImp struct{}

func (l *LoginServerImp) Login(ctx context.Context, token *proto.ReqGetToken) (*proto.ResGetToken, error) {
	code := token.Code
	fmt.Println(code)
	res := &proto.ResGetToken{
		Token: code + "hello",
	}
	return res, nil

}

func main() {
	grpcSever := grpc.NewServer()
	proto.RegisterHelloServiceServer(grpcSever, new(HelloServiceImpl))
	proto.RegisterLoginServiceServer(grpcSever, new(LoginServerImp))

	lis, err := net.Listen("tcp", ":1234")
	if err != nil {
		log.Fatal(err)
	}
	grpcSever.Serve(lis)
}
